<template>
  <div id="tableFilter">
    <a-form
      ref="formRef"
      name="advanced_search"
      class="ant-advanced-search-form"
      :model="formState"
      @finish="onFinish"
    >
      <a-row align="middle" :gutter="16">
        <a-col flex="11">
          <a-row :gutter="24">
            <a-col
              v-for="(field, index) in filteredConfig"
              :key="index"
              :span="field.span || 8"
            >
              <a-form-item :name="field.name" :label="field.label">
                <!-- 輸入框 -->
                <a-input
                  v-if="field.type === 'input'"
                  v-model:value="formState[field.name]"
                  :placeholder="field.placeholder"
                />
                <!-- 下拉框 -->
                <a-select
                  v-else-if="field.type === 'select'"
                  v-model:value="formState[field.name]"
                  showSearch
                  :options="field.options"
                />
                <!-- 月份選擇器 -->
                <a-date-picker
                  v-model:value="formState[field.name]"
                  v-else-if="field.type === 'date-picker'"
                  :placeholder="field.placeholder"
                  :picker="field.picker"
                  :valueFormat="getValueFormat(field.picker)"
                />

                <!-- 時間日期範圍選擇器 -->
                <a-range-picker
                  v-else-if="field.type === 'range-picker'"
                  v-model:value="formState[field.name]"
                  :show-time="field.showTime"
                  :placeholder="field.placeholder"
                  valueFormat="YYYY-MM-DD"
                />
                <!-- 多選框 -->
                <a-checkbox-group
                  v-else-if="field.type === 'checkbox-group'"
                  v-model:value="formState[field.name]"
                  :options="field.options"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-divider
          type="vertical"
          style="height: 60px; background-color: #ccc"
        />

        <a-col flex="1">
          <a-space direction="vertical">
            <a-button type="primary" html-type="submit"
              ><template #icon> <SearchOutlined /> </template>搜索</a-button
            >
            <a-button @click="() => formRef?.resetFields()">
              <template #icon> <RedoOutlined /></template>重置</a-button
            >
          </a-space></a-col
        >
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from "vue";
import { SearchOutlined, RedoOutlined } from "@ant-design/icons-vue";
import type { FormInstance } from "ant-design-vue";
import { useRoute } from "vue-router";
import { useAuthUserStore } from "@/store/authUserStore";

const userInfo = useAuthUserStore().userInfo;
const isDoctor = userInfo.roles.includes("Doctor");

// 定義字段配置類型
export interface FieldConfig {
  name: string;
  label: string;
  type: "input" | "select" | "checkbox-group" | "date-picker" | "range-picker";
  placeholder?: string | Array<string>;
  options?: { value: any; label: string }[];
  showTime?: boolean;
  span?: number;
  picker?: "year" | "month" | "quarter" | "week" | "date";
}

// 定義 props
const props = defineProps<{
  config: FieldConfig[];
}>();

const filteredConfig = computed(() => {
  if (isDoctor) {
    // 過濾掉staff_code和doctor_name字段
    return props.config.filter(
      (field) => !["staff_code", "doctor_name"].includes(field.name)
    );
  }
  return props.config;
});

const route = useRoute();
// 初始化表單狀態
const formState = reactive(
  filteredConfig.value.reduce((state, field) => {
    state[field.name] =
      route.query[field.name] || (field.type === "checkbox-group" ? [] : "");
    // console.log(typeof(field.name,route.query[field.name]))
    if (field.type === "range-picker") {
      state[field.name] = route.query[field.name]
        ? [route.query[field.name + "_start"], route.query[field.name + "_end"]]
        : [];
    }
    return state;
  }, {} as Record<string, any>)
);

const formRef = ref<FormInstance>();
const emit = defineEmits(["search"]);

const onFinish = (values: any) => {
  emit("search", deepFilter(values));
};

// 深度過濾空值 (同時保留有效值為 0 或 false)
const deepFilter = (obj: any) => {
  return Object.keys(obj).reduce((acc: any, key) => {
    const value = obj[key];
    if (value !== null && value !== undefined && value !== "") {
      acc[key] = typeof value === "object" ? deepFilter(value) : value;
    }
    return acc;
  }, {});
};

const getValueFormat = (picker: string) => {
  switch (picker) {
    case "year":
      return "YYYY";
    case "month":
      return "YYYY-MM";
    case "quarter":
      return "YYYY-[Q]Q";
    case "week":
      return "YYYY-[W]WW";
    case "date":
      return "YYYY-MM-DD";
    default:
      return "YYYY-MM-DD";
  }
};
</script>

<style scoped>
#tableFilter {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px;
  border-radius: 10px;
}
</style>
